package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class FriendApiImpl implements FriendApi{

    @Autowired
    private MongoTemplate mongoTemplate;


    //双向保存好友信息
    @Override
    public void save(Long userId, Long friendId) {
        //保存好友关系 需要双向保存
        //保存自己和好友的关系
        Query myQuery = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        //判断好友关系是否存在
        if (!mongoTemplate.exists(myQuery, Friend.class)){
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            friend.setCreated(System.currentTimeMillis());

            mongoTemplate.save(friend);
        }

        //保存好友和自己的关系
        Query friendQuery = Query.query(Criteria.where("userId").is(friendId).and("friendId").is(userId));
        //判断好友关系是否存在
        if (!mongoTemplate.exists(friendQuery, Friend.class)){
            Friend friend = new Friend();
            friend.setUserId(friendId);
            friend.setFriendId(userId);
            friend.setCreated(System.currentTimeMillis());

            mongoTemplate.save(friend);
        }
    }

    //删除好友关系
    @Override
    public void remove(Long userId, Long friendId) {
        //删除好友关系 需要双向删除
        //删除自己和好友的关系
        Query myQuery = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        mongoTemplate.remove(myQuery,Friend.class);

        //删除好友和自己的关系
        Query friendQuery = Query.query(Criteria.where("userId").is(friendId).and("friendId").is(userId));
        mongoTemplate.remove(friendQuery,Friend.class);
    }

    //根据userId查询所有的好友
    @Override
    public List<Long> findByUserId(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        List<Long> collect = friends.stream().map(Friend::getFriendId).collect(Collectors.toList());
        return collect;
    }
}
